package com.boot.ys.mybatisplus.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boot.ys.mybatisplus.entity.Role;
import com.boot.ys.mybatisplus.entity.User;
import com.boot.ys.mybatisplus.entity.vo.IdCardVO;
import com.boot.ys.mybatisplus.mapper.RoleMapper;
import com.boot.ys.mybatisplus.mapper.UserMapper;
import com.boot.ys.mybatisplus.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Yang Sheng
 * @since 2021-10-25
 */
@Slf4j
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<User> getAll() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("state", 0);
        List<User> collect = userMapper.selectList(queryWrapper);

        return collect;
    }

    //同时更新两张表
    @Override
    public Boolean updateToTab() {
        boolean value = false;

        Role role = new Role();
        role.setRoleDescription("更新成功");
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", 1);
        int updateRole = roleMapper.update(role, queryWrapper);
        System.out.println("updateRole:" + updateRole);

        User user = new User();
        user.setUserId(2);
        QueryWrapper queryWrapperr = new QueryWrapper();
        queryWrapperr.eq("user_id", 1);
        int updateUser = userMapper.update(user, queryWrapperr);
        System.out.println("updateUser:" + updateUser);

        if (updateRole >= 1 && updateUser >= 1) {
            value = true;
        }
        return value;
    }

    //更新表里面的数据
    @Override
    public int updateUser(User user) {

//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("user_name",user.getUserName());

//        User u = new User();
//        u.setAddress("测试地址");
//        int isBoolean = userMapper.update(u,queryWrapper);
        int i = userMapper.updateMyself(user);

        return i;
    }

    /**
     * 数字藏品里面的接口  调用天眼的实名验证
     *
     * @param arr
     */
    @Override
    public void IdCardValidate(IdCardVO idCard) throws IOException {
        String url = "https://eid.shumaidata.com/eid/check";
        //去找后台配置
        String appCode = "d1e9f49af53b4d19b835d36ec0e95725";
        Map<String, String> params = new HashMap<>();
        params.put("idcard", idCard.getCardId());
        params.put("name", idCard.getCardName());
        String result = postForm(appCode, url, params);
        log.info("天眼实名认证的Code为：{}，地址为：{}，验证的姓名和身份证号为：{}", appCode, url, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        //判断天眼实名认证返回的状态是否为1，如果是则信息一致进行添加，否则输入信息不一致
        if (!StringUtils.isEmpty((CharSequence) jsonObject.getJSONObject("result"))) {
            String res = (String) jsonObject.getJSONObject("result").get("res");
            if (StringUtils.isEmpty(res)) {
                log.info("实名认证失败，输入的姓名{}，输入的身份证号{}，认证返回的参数{}", idCard.getCardName(), idCard.getCardId(), jsonObject);
                log.info("实名认证失败！！！");
            }
            Integer parseInt = Integer.parseInt(res);
            //判断天眼实名认证返回的状态是否为1，如果是则信息一致进行添加，否则输入信息不一致s
            if (parseInt == 1) {
                //处理自己的业务逻辑，实名信息验证成功
                //TODO

            } else {
                log.info("认证失败！请检查信息输入是否有误！");
            }
        }

    }

    /**
     * 天眼实名认证
     *
     * @param appCode
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public String postForm(String appCode, String url, Map<String, String> params) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            formbuilder.add(key, params.get(key));
        }
        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(body).build();
        Response response = client.newCall(request).execute();
        String result = response.body().string();
        return result;
    }


}
